<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use App\Models\video\BroadcasterModel;
use App\Models\video\BroadcasterRelationModel;
use App\Models\video\CommentModel;
use App\Models\video\CommonServer;
use App\Models\video\OperateModeModel;
use App\Models\video\PlayClassModel;
use App\Models\video\PlayListModel;
use App\Models\video\ReplyModel;
use App\Models\video\SubscriptionModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VodVideoModel;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class BroadcasterController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['getBroadcasterInfo', 'getPlayClassList', 'getPlayVideoList']; //不校验openid
        parent::__construct($request);
    }

    // 获取up主用户基本信息
    public function getBroadcasterInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if ($request->token) {
            $userId = $this->getTokenVar($request->token, "id");
            if (!$userId) {
                return $this->return_result($this->returnData);
            }
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($settingData["operateMode"] == '1'){
            $filter = ["id" => BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1])];
        }else {
            if ($request->token) {
                $filter = ["user_id" => $userId];
            } else {
                if ($request->id) {
                    $filter = ["id" => $request->id ?: 0];
                } else {
                    $filter = ["id" => BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1])];
                }
            }
        }
        $data = BroadcasterModel::getFields('id,name,bg_image_id,avatar_id,desc,fan_number,status,register_time,color,list_show_mode,wxapp_color,wxapp_title,home_show_mode,video_show_mode,home_font_color', $filter);
        $data["subscribe"] = 0; // 未订阅
        $data["remindStatus"] = 0; // 提醒状态
        if(!empty($userId)) {
            $tempData = SubscriptionModel::getFields("remind_status", ["broadcaster_id" => $data["id"], "user_id" => $userId]);
            if (!empty($tempData)) {
                $data["subscribe"] = 1; // 已订阅
                $data["remindStatus"] = intval($tempData["remindStatus"]); // 提醒状态
            }
            $data["videoCount"] = VodVideoModel::query()->where(["broadcaster_id" => $data["id"], "status" => 1])->count();
            $data["praiseCount"] = OperateModeModel::from(OperateModeModel::query()->getModel()->getTable()." as o")
                ->leftJoin(VodVideoModel::query()->getModel()->getTable(). " as v", "v.id", "=", "o.belong_id")
                ->where(["v.broadcaster_id" => $data["id"], "o.type" => 4, "o.mode" => 1])
                ->count();
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    public function updateBroadcasterInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主ID"));
        }
        if(empty($request->name)){
            return $this->return_result(ErrorCode::code("params_not_exist", "up主昵称"));
        }
        $data = ["name" => $request->name];
        if(!empty($request->bgImageId)){
            $data["bg_image_id"] = $request->bgImageId;
        }
        if(!empty($request->color)){
            $data["color"] = $request->color;
        }
        if(!empty($request->avatarId)){
            $data["avatar_id"] = $request->avatarId;
        }
        if(!empty($request->desc)){
            $data["desc"] = $request->desc;
        }
        if(!empty($request->wxappColor)){
            $data["wxapp_color"] = $request->wxappColor;
        }
        if(!empty($request->listShowMode)){
            $data["list_show_mode"] = $request->listShowMode;
        }
        if(!empty($request->wxappTitle)){
            $data["wxapp_title"] = $request->wxappTitle;
        }
        if(!empty($request->homeShowMode)){
            $data["home_show_mode"] = $request->homeShowMode;
        }
        if(!empty($request->videoShowMode)){
            $data["video_show_mode"] = $request->videoShowMode;
        }
        if(!empty($request->homeFontColor)){
            $data["home_font_color"] = $request->homeFontColor;
        }
        if(!BroadcasterModel::doUpdate($data, ["id" => $request->id])){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '更新失败';
        }
        return $this->return_result($this->returnData);
    }

    // 添加播放列表
    public function addPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->name){
            return $this->return_result(ErrorCode::code("params_not_exist", "名称"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $data = ["broadcaster_id" => $broadcasterId, "name" => $request->name];
        if($request->payMoney){
            $data["pay_money"] = $request->payMoney;
            $data["pay_mode"] = 1;
        }
        $id = PlayClassModel::toAdd($data, true);
        $this->returnData["data"] = ["id" => $id];
        return $this->return_result($this->returnData);
    }

    // 删除播放列表
    public function delPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "分类列表ID"));
        }
        PlayClassModel::delById($request->id);
        return $this->return_result($this->returnData);
    }

    // 收藏视频和稍后观看视频
    public function playToCollectVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->videoId){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        $classId = isset($request->classId) ? $request->classId : 0;
        if(!VodVideoModel::query()->where("id", $request->videoId)->count()){
            return $this->return_result(ErrorCode::code("customized", "视频不存在"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $data = PlayListModel::getFields("id", ["broadcaster_id" => $broadcasterId, "video_id" => $request->videoId, "class_id" => $classId]);
        if($data){
            return $this->return_result(ErrorCode::code("customized", "视频已经存在于列表"));
        }
        PlayListModel::toAdd(["broadcaster_id" => $broadcasterId, "video_id" => $request->videoId, "class_id" => $classId]);
        return $this->return_result($this->returnData);
    }

    // 移除视频
    public function playToRemoveVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->videoId){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $classId = isset($request->classId) ? $request->classId : 0;
        $data = PlayListModel::getFields("id,class_id,video_id", ["broadcaster_id" => $broadcasterId, "video_id" => $request->videoId, "class_id" => $classId]);
        if($data){
            PlayListModel::delById($data["id"], $data);
        }
        return $this->return_result($this->returnData);
    }

    // 我的播放分类列表
    public function getPlayClassList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($settingData["operateMode"] == '1'){
            $broadcasterId = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
        }else {
            if ($request->token) {
                $userId = $this->getTokenVar($request->token, "id");
                if (!$userId) {
                    return $this->return_result($this->returnData);
                }
                $broadcaster = CommonServer::judgeUpIdentity($userId, request()->mallData["id"]);
                $broadcasterId = $broadcaster ?: 0;
            } else {
                $broadcasterId = $request->id ?: 0;
            }
        }
        $playClassData = PlayClassModel::getList("id,name,num", ["broadcaster_id" => $broadcasterId], $request->page ?: 1, $request->pageSize ?: 10);
        foreach ($playClassData["list"] as &$item){
            $item["imgUrl"] = "";
            $data = PlayListModel::from("up_play_list as pl")->leftJoin("up_vod_video as v", "v.id", "=", "pl.video_id")
                ->where(["pl.class_id" => $item["id"], "pl.mall_id" => $request->mallData["id"]])
                ->select(["v.cover_img_id"])->orderBy("v.id", "desc")
                ->first();
            if(!empty($data)){
                $data = VodVideoModel::transferField($data->toArray());
                $item["imgUrl"] = $data["coverImgUrl"];
            }
        }
        $this->returnData["data"] = $playClassData["list"];
        return $this->return_result($this->returnData);
    }

    // 我的所有播放分类列表
    public function getAllPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($settingData["operateMode"] == '1'){
            $broadcasterId = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
        }else {
            if ($request->token) {
                $userId = $this->getTokenVar($request->token, "id");
                if (!$userId) {
                    return $this->return_result($this->returnData);
                }
                $broadcaster = BroadcasterModel::from(BroadcasterModel::query()->getModel()->getTable()." as b")
                    ->leftJoin(BroadcasterRelationModel::query()->getModel()->getTable()." as br", "b.id", "=", "br.broadcaster_id")
                    ->where(["b.mall_id" => request()->mallData["id"], "br.user_id" => $userId])
                    ->select("b.id")->first();
                $broadcasterId = $broadcaster->id;
            } else {
                $broadcasterId = $request->id ?: 0;
            }
        }
        $playClassData = PlayClassModel::getFields("id,name", ["broadcaster_id" => $broadcasterId], false, false);
        if(empty($playClassData)){
            $playClassData = [["id" => 0, "name" => "默认"]];
        }
        $this->returnData["data"] = $playClassData;
        return $this->return_result($this->returnData);
    }

    // 我的视频播放列表
    public function getPlayVideoList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($settingData["operateMode"] == '1'){
            $broadcasterId = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
        }else {
            if ($request->token) {
                $userId = $this->getTokenVar($request->token, "id");
                if (!$userId) {
                    return $this->return_result($this->returnData);
                }
                $broadcaster = BroadcasterModel::from(BroadcasterModel::query()->getModel()->getTable()." as b")
                    ->leftJoin(BroadcasterRelationModel::query()->getModel()->getTable()." as br", "b.id", "=", "br.broadcaster_id")
                    ->where(["b.mall_id" => request()->mallData["id"], "br.user_id" => $userId])
                    ->select("b.id")->first();
                $broadcasterId = $broadcaster->id;
            } else {
                if ($request->id) {
                    $broadcasterId = $request->id;
                } else {
                    $broadcasterId = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
                }
            }
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $sortField = $request->sortField ? Str::snake($request->sortField) : "create_time";
        $sortType = $request->sortType ?: "desc";
        if($request->classId){
            $db = PlayListModel::from("up_play_list as pl")->leftJoin("up_vod_video as v", "v.id", "=", "pl.video_id")
                ->where(["pl.broadcaster_id" => $broadcasterId, 'pl.class_id' => $request->classId, "v.status" => 1])
                ->select(["v.id","v.title","v.cover_img_id","v.desc","v.view_count","v.video_length", 'v.broadcaster_id','v.create_time'])
                ->orderBy("pl.".$sortField, $sortType);
            $data['count'] = $db->count();
            $data['currentPage'] = $page;
            $data['totalPage'] = ceil(($data['count'])/$pageSize);
            $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("pl.create_time", "desc")->get();
            if($data['list']){
                $data['list'] = VodVideoModel::transferField($data['list']->toArray());
            }
            $info = PlayClassModel::getFields("broadcaster_id,create_time", ["id" => $request->classId]);
            $data["info"] = ["createTime" => !empty($info["createTime"]) ? $info["createTime"] : "", "founder" => !empty($info["broadcasterName"]) ? $info["broadcasterName"] : ""];
        }else{
            $data = VodVideoModel::getList(
                "id,title,cover_img_id,desc,view_count,video_length,broadcaster_id,create_time",
                ["broadcaster_id" => $broadcasterId, "status" => 1, "handle_result" => 2, "type" => 1], $page, $pageSize, $sortField, $sortType);
            if(!empty(!empty($data["list"][0]))){
                $data["info"] = ["createTime" => $data["list"][0]["createTime"], "founder" => $data["list"][0]["broadcasterName"]];
            }else{
                $data["info"] = ["createTime" => '', "founder" => ''];
            }
        }
        foreach ($data["list"] as &$item){
            $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "type" => 1, "status" => 1, "mall_id" => $request->mallData["id"]]) +
                ReplyModel::from(ReplyModel::query()->getModel()->getTable(). " as r")
                    ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                    ->where(["c.belong_id" => $item["id"], "r.status" => 1])
                    ->count();
            $item["createTime"] = UpTools::handleTimeToText($item["createTime"]);
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }
}